package webdev.fragment;

import java.util.ArrayList;

import webdev.adapters.SearchListAdapter;
import webdev.common.Common;
import webdev.database.SQLQuery;
import webdev.dto.DiaDiemDTO;
import webdev.utils.ConvertUnsigned;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import dev.danang.R;

public class SearchNavigationFragment extends Fragment implements
		OnClickListener {

	private EditText mEditTextSearch;
	private ProgressBar mProgressBar;
	private ProgressBar mProgressBarLoadMore;
	private ListView mListViewSearch;
	private SearchListAdapter mSearchAdapter;
	private SearchListAdapter mListAdapter;
	ImageView imageViewClearTextSearch;
	private ArrayList<DiaDiemDTO> mSearchResults;
	private TextView mTextViewCancel;
	private View footer;
	ConvertUnsigned clsConvert;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View layout = inflater
				.inflate(R.layout.youlook_search_navigation, null);
		clsConvert = new ConvertUnsigned();
		init(layout);
		setValue();
		setEventForMembers();
		
		return layout;
	}

	private void init(View layout) {
		mEditTextSearch = (EditText) layout
				.findViewById(R.id.right_navigation_search_view);
		mProgressBar = (ProgressBar) layout
				.findViewById(R.id.progress_bar_search);
		mListViewSearch = (ListView) layout.findViewById(R.id.list_view_search);
		imageViewClearTextSearch =(ImageView)layout.findViewById(R.id.image_view_clear_text_search);
		mSearchResults = new ArrayList<DiaDiemDTO>();
		mSearchAdapter = new SearchListAdapter(getActivity());
		mListAdapter = new SearchListAdapter(getActivity());
		mTextViewCancel = (TextView) layout
				.findViewById(R.id.text_view_search_cancel);

		// init a footer for list view
		footer = ((LayoutInflater) getActivity().getSystemService(
				Context.LAYOUT_INFLATER_SERVICE)).inflate(
				R.layout.footer_list_view_landing_page, null, false);

		mProgressBarLoadMore = (ProgressBar) footer
				.findViewById(R.id.progress_bar_landing_page_load_more);
		new ProccessingData(getActivity(), Common.TAB_ForSearch).execute();
	}

	private void setValue() {
		// add footer load more for list view
		footer.setBackgroundColor(getResources().getColor(R.color.color_black));
		mListViewSearch.addFooterView(footer);
		mListViewSearch.setAdapter(mSearchAdapter);
		mProgressBar.setVisibility(View.GONE);
		mProgressBarLoadMore.setVisibility(View.GONE);
	}

	private void setEventForMembers() {
		mEditTextSearch.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				mSearchResults.clear();
				mSearchAdapter.notifyDataSetChanged();
			}

			@Override
			public void afterTextChanged(Editable s) {
				String mKeyWord = mEditTextSearch.getText().toString().trim();
				String textSearch = clsConvert.ConvertString(mKeyWord);
				if (mKeyWord.length() >= 3) {
					new ProccessingDataSearch(getActivity(), textSearch, Common.TAB_ForSearch)
							.execute();
				} else {
					mListViewSearch.setAdapter(mListAdapter);
				}
			}
		});

		mEditTextSearch.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if ((event.getKeyCode() == KeyEvent.KEYCODE_SEARCH)
						|| (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
					String mKeyWord = mEditTextSearch.getText().toString()
							.trim();
					String textSearch = clsConvert.ConvertString(mKeyWord);
					if (mKeyWord.length() >= 3) {
						new ProccessingDataSearch(getActivity(), textSearch, Common.TAB_ForSearch)
								.execute();
					} else {
						mListViewSearch.setAdapter(mListAdapter);
					}
				}
				return false;
			}
		});
		imageViewClearTextSearch.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mEditTextSearch.setText("");
				mListViewSearch.setAdapter(mListAdapter);
				hideSoftKeyboard();
			}
		});
		mListViewSearch.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long id) {
			}
		});
		mTextViewCancel.setOnClickListener(this);
	}
	/* (non-Javadoc)
	 * @see android.support.v4.app.Fragment#onResume()
	 */
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		new ProccessingData(getActivity(), Common.TAB_ForSearch).execute();
		super.onResume();
		
	}
	public void callReload()
	{
		new ProccessingData(getActivity(), Common.TAB_ForSearch).execute();
	}
	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.text_view_search_cancel) {
			hideSoftKeyboard();
		} else {
			// go to detail
		}
	}

	private void hideSoftKeyboard() {
		InputMethodManager imm = (InputMethodManager) getActivity()
				.getSystemService(Service.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(mEditTextSearch.getWindowToken(), 0);
	}

	/**
	 * Background Async Task to process data
	 * */
	class ProccessingData extends AsyncTask<Void, Void, Boolean> {

		/**
		 * Before starting background thread Show Progress Bar Dialog
		 * */
		ProgressDialog pDialog;
		ArrayList<DiaDiemDTO> arrCatagory;
		Context mContext;
		int mType;

		public ProccessingData(Context context, int type) {
			mType = type;
			mContext = context;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			arrCatagory = new ArrayList<DiaDiemDTO>();
			pDialog = new ProgressDialog(mContext);
			pDialog.setMessage("Đang xử lý...");
			pDialog.setCancelable(true);
			pDialog.setIcon(R.drawable.ic_launcher);
			pDialog.show();
		}

		/**
		 * Processing data in background thread
		 * */
		@Override
		protected Boolean doInBackground(Void... f_url) {
			SQLQuery query = new SQLQuery(mContext);
			arrCatagory = query.getAllDiaDiem(mType);
			if (arrCatagory != null && arrCatagory.size() > 0) {
				return true;
			} else {
				return false;
			}
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			pDialog.dismiss();
			if (result) {
				mListAdapter.clearAll();
				for (int i = 0; i < arrCatagory.size(); i++) {
					mListAdapter.addItem(arrCatagory.get(i));
				}
				mListAdapter.notifyDataSetChanged();
				mListViewSearch.setAdapter(mListAdapter);
			} else {
				mListAdapter.clearAll();
				mListAdapter.notifyDataSetChanged();
				Toast.makeText(mContext, "Không tồn tại dữ liệu",
						Toast.LENGTH_SHORT).show();
			}
			onCancelled();
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

	/**
	 * Background Async Task to process data
	 * */
	class ProccessingDataSearch extends AsyncTask<Void, Void, Boolean> {

		/**
		 * Before starting background thread Show Progress Bar Dialog
		 * */
		ProgressDialog pDialog;
		ArrayList<DiaDiemDTO> arrCatagory;
		Context mContext;
		String mtextSearch;
		int mType;
		public ProccessingDataSearch(Context context, String txtSearch, int type) {
			mContext = context;
			mtextSearch = txtSearch;
			mType = type;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			arrCatagory = new ArrayList<DiaDiemDTO>();
			pDialog = new ProgressDialog(mContext);
			pDialog.setMessage("Đang xử lý...");
			pDialog.setCancelable(true);
			pDialog.setIcon(R.drawable.ic_launcher);
			pDialog.show();
		}

		/**
		 * Processing data in background thread
		 * */
		@Override
		protected Boolean doInBackground(Void... f_url) {
			SQLQuery query = new SQLQuery(mContext);
			arrCatagory = query.getAllDiaDiemSearch(mType,mtextSearch);
			if (arrCatagory != null && arrCatagory.size() > 0) {
				return true;
			} else {
				return false;
			}
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			pDialog.dismiss();
			if (result) {
				mSearchAdapter.clearAll();
				for (int i = 0; i < arrCatagory.size(); i++) {
					mSearchAdapter.addItem(arrCatagory.get(i));
				}
				mSearchAdapter.notifyDataSetChanged();
				mListViewSearch.setAdapter(mSearchAdapter);
			} else {
				mSearchAdapter.clearAll();
				mSearchAdapter.notifyDataSetChanged();
				Toast.makeText(mContext, "Không tồn tại dữ liệu",
						Toast.LENGTH_SHORT).show();
			}
			onCancelled();
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

}
